//
//  WBUserAccount.swift
//  weibo
//
//  Created by iobit on 2017/07/03.
//  Copyright © 2017 zhuxu. All rights reserved.
//

import UIKit
/// 用户账户信息

private let accountFile:NSString = "useraccount.json"

class WBUserAccount: NSObject {
    
    // 访问令牌
    var access_token: String? //= "2.00dMCoYGgCFz5E3527160bebvFGUvB"
    
    // access_token的生命周期，单位是秒数，会一直减小
    // 开发者的账号过期时间为5年，其他测试者为3天
    var expires_in: TimeInterval = 0 {
        didSet {
            expiresDate = Date(timeIntervalSinceNow: expires_in)
        }
    }
    
    // 用户uid
    var uid: String?
    
    // 过期日期,不会变
    var expiresDate:Date?
    
    // 用户昵称
    var screen_name:String?
    
    // 用户头像地址（大图），180×180像素
    var avatar_large:String?
    
    override var description: String {
        return yy_modelDescription()
    }
    
    
    override init() {
        super.init()
        // 1\获取文件路径
        // 2\转换为data
        // 3\反序列化为字典
        guard let path = accountFile.cz_appendDocumentDir(),
            let data = NSData(contentsOfFile: path),
            let dic = try? JSONSerialization.jsonObject(with: data as Data, options: []) as? [String: Any] else {
            return
        }
        // 4\设置属性
        // **** 用户是否登录的关键代码
        self.yy_modelSet(withJSON: dic ?? [:])
        
        print("从沙盒json文件加载设置用户信息，\(self)")
        
        // 判断token是否过期
//        expiresDate = Date(timeIntervalSinceNow: -3600*24)//测试过期
        if expiresDate?.compare(Date()) != .orderedDescending{
            print("账户过期")
            //清空token
            access_token = nil
            uid = nil
            //删除账户文件
            try? FileManager.default.removeItem(atPath: path)
        }
        
    }
    
    
    /*
     1、偏好设置(小数据)
     2、沙盒-归档、plist、json
     3、数据库(FMDB/CoreData)
     4、钥匙串访问(小数据、自动加密-需要使用框架SSKeychain)
     */
    func saveAccount() {
        //模型转字典
        var dict = self.yy_modelToJSONObject() as? [String: Any] ?? [:]
        //删除expires_in值
        dict.removeValue(forKey: "expires_in")
        //字典序列化转data
        guard let data = try? JSONSerialization.data(withJSONObject: dict, options: []),
        let filePath = accountFile.cz_appendDocumentDir() else{
            return
        }
        // 写入磁盘
        (data as NSData).write(toFile: filePath, atomically: true)
        print("用户账户保存成功\(filePath)")
        
    }
    
}
